package tk.mybatis.springboot.spider.pipeline;


import com.alibaba.fastjson.JSON;
import com.virjar.vscrawler.core.seed.Seed;
import com.virjar.vscrawler.core.serialize.Pipeline;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.springboot.service.YService;
import tk.mybatis.springboot.spider.entity.ErrorEntity;
import tk.mybatis.springboot.spider.entity.ImowProductEntity;

import java.util.Collection;

@Component("yPipeline")
public class YPipeline implements Pipeline {

    public YPipeline() {
    }

    public YPipeline(YService yService) {
        this.yService = yService;
    }

    @Autowired
    private YService yService;

    private int i = 0;

    @Override
    public void saveItem(Collection<String> itemJson, Seed seed) {
        for (String str : itemJson) {
            System.out.println("==========保存数据==========");
            System.out.println(str);
            if (str.contains("errorLink") && str.contains("errorType")) {
                saveEntity(null, JSON.parseObject(str, ErrorEntity.class));
            } else {
                saveEntity(JSON.parseObject(str, ImowProductEntity.class), null);
            }
        }
    }

    /**
     * 保存数据
     */
    public void saveEntity(ImowProductEntity productEntity, ErrorEntity errorEntity) {
        if (null != productEntity) {
            yService.saveImow(productEntity);
        }

        if (null != errorEntity) {
            yService.saveErrorLink(errorEntity);
        }
    }
}
